<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import NavTop from '../components/popup/NavTop.vue'
import PopupTop from '../components/popup/PopupTop.vue'
import SearchTop from '../components/popup/SearchTop.vue'
import PopupBottom from '../components/popup/PopupBottom.vue'
import { ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'

import { deepClone, parseJson, validateJson } from '../utils/json'
import { settingRequest } from '../utils/fetch'

const popup = reactive({
    iframe: {
        element: null as any,
        src: ''
    },
    webview: {
        element: null as any,
        src: ''
    },
    visible: false,
    vertical: false, // 竖屏模式
    hidden: false,
    menus: [] as Array<Collection>,
    autoFullScreen: false,
    borderRadius: false,
    theme: 'image',
    version: '',
    appName: 'Fish-Ads-App',
    count: 1,
    verticalWebsiteHost: [] as Array<string>
})

const toggleAds = () => {
    const webview = popup.webview.element,
        iframe = popup.iframe.element

    popup.hidden = !popup.hidden
    popup.iframe.src = handleAdsSrc(popup.iframe.src)
    iframe.style.height = popup.hidden ? 'calc(100vh - 39px - 57px)' : '162px'
    webview.style.display = popup.hidden ? 'none' : 'flex'
    window.F.hidden = popup.hidden

    webview.executeJavaScript(`
        document.querySelectorAll('video').forEach(video => ${window.F.hidden ? 'video.pause()' : 'video.play()'})
    `, true)
}

const handleAdsSrc = (src: string) => {
    let url = new URL(src),
        href = url.origin + url.pathname

    return `${href}?v=${popup.version}&type=${popup.hidden ? 'big' : popup.theme}`
}

const handleShip = (visible: boolean, vertical: boolean) => {
    const webview = popup.webview.element

    popup.vertical = vertical
    popup.visible = visible

    webview.classList.toggle('nav', !visible)
    webview.classList.toggle('fish', visible)

    if (visible) {
        vertical && webview.classList.add('vertical')
    } else {
        popup.hidden = !visible
        webview.executeJavaScript(`${popup.autoFullScreen} && setTimeout(toggleFullScreen, 0)`, true)
        webview.classList.remove('vertical')
        toggleAds()

        // 说点垃圾话
        popup.appName = [
            '看看捞点啥鱼呢？',
            '又是能量满满的一天~',
            '温馨提示：不安全的话请勿置顶哦~',
            '好想下班~',
            '听，是假期的号角声~',
            '肚子咕咕叫了，是在提醒我该吃点啥吗？',
            '厕所也是摸鱼的好去处~',
            '周末的计划在脑子里打转啦～',
            '喝口茶歇会儿，感觉又能再干亿会儿～',
            '假装自己是 Google 窗口，不会被发现吧~'
        ][randomNumber(0, 9, [])]
    }

    window.F.visible = visible
}

const handleStar = (menus: Array<Collection>) => {
    popup.menus = menus
    window.ipcRenderer.send('set-config', deepClone({ menus: menus }))
}

const handleQuit = () => {
    window.ipcRenderer.send('close-all-windows')
}

const randomNumber = (min: number, max: number, exclude: any) => {
    var number
    do {
        number = Math.floor(Math.random() * (max - min + 1)) + min
    } while (exclude && exclude.includes(number))
    return number
}

onMounted(async () => {
    window.F = {
        visible: false,
        hidden: false,
        toggleAds: toggleAds
    }

    popup.iframe.element = document.getElementById('ads')
    popup.webview.element = document.getElementById('website')

    let config = await window.ipcRenderer.invoke('read-config')
    popup.menus = config.menus
    popup.theme = config.theme
    popup.autoFullScreen = config.autoFullScreen
    popup.borderRadius = config.borderRadius
    popup.version = config.version
    popup.appName = popup.appName + ` - ${config.version}`
    window.F.verticalWebsiteHost = config.verticalWebsiteHost || 'www.douyin.com'
    document.body.style.opacity = `${config.opacity}`
    if (config.source) {
        popup.iframe.src = handleAdsSrc(config.source)
    }
    if (config.home) {
        popup.webview.src = config.home
    }
    if (config.verticalWebsiteHost) {
        popup.verticalWebsiteHost = config.verticalWebsiteHost.split(',')
    }
    if (!config.read) {
        ElMessageBox.alert(`感谢您的使用，当前版本为 ${config.version}，本应用完全免费且开源，请勿用于任何商业用途！如果喜欢的话可以分享或者给作者点赞，十分感谢！`, '欢迎使用', {
            confirmButtonText: '我已知晓',
            callback: (action: Action) => {
                if (action === 'confirm') {
                    config.read = true
                    window.ipcRenderer.send('set-config', deepClone(config))
                }
            },
        })
    }
    // 加载扩展程序
    config.extensionPath && window.ipcRenderer.send('load-extension')

    window.addEventListener('message', function (event) {
        if (event.data.app === 'fish-ads-app' && event.data.type === 'counter') {
            if (event.data.counter) {
                popup.count = event.data.counter.member
            }
        }
    })

    config.read && fetch(settingRequest).then(response => response.json()) // 解析 JSON 数据
        .then((data: any) => { // 处理数据
            // 校验 json 格式
            if (validateJson(data.body, true)) {
                data.body = parseJson(data.body) // 解析、转义
                data.body = JSON.stringify(data.body, null, 2)
            }
            let setting = JSON.parse(data.body), activateNotice = function (notice: any) {
                if (config.notices && config.notices.length > 0) {
                    for (let i = 0; i < config.notices.length; i++) {
                        if (config.notices[i].id === notice.id) {
                            return false
                        }
                    }
                } else {
                    config.notices = []
                }
                if (notice.condition === '<' && notice.version > popup.version) {
                    return true
                } else if (notice.condition === '>' && notice.version < popup.version) {
                    return true
                } else if (notice.condition === '=' && notice.version === popup.version) {
                    return true
                }
                return false
            }
            if (setting.notices && setting.notices.length > 0) {
                for (const notice of setting.notices) {
                    if (activateNotice(notice)) {
                        ElMessageBox.alert(notice.content, '通知公告', {
                            confirmButtonText: '我已知晓',
                            callback: (action: Action) => {
                                if (action === 'confirm') {
                                    config.notices.splice(0, 0, notice)
                                    window.ipcRenderer.send('set-config', deepClone(config))
                                }
                            },
                        })
                        break
                    }
                }
            }
        }).catch((error: any) => console.error(error))
})
</script>

<template>
    <div class="popup" :style="{
        'border-radius': popup.borderRadius ? '8px' : '0px'
    }">
        <nav-top v-if="!popup.visible" :app-name="popup.appName" close-type="danger" @quit="handleQuit" />
        <search-top :menus="popup.menus" :vertical-website-host="popup.verticalWebsiteHost" :count="popup.count"
            :src="popup.webview.src" :auto-full-screen="popup.autoFullScreen" v-if="!popup.visible" @ship="handleShip"
            @star="handleStar" />
        <popup-top v-if="popup.visible" @ship="handleShip" @hidden="toggleAds" />
        <iframe v-show="popup.visible && (!popup.vertical || popup.hidden)" id="ads" :src="popup.iframe.src"
            scrolling="no"></iframe>
        <webview class="nav" :src="popup.webview.src" id="website" allowpopups></webview>
        <popup-bottom v-if="popup.visible && !popup.vertical" />
    </div>
</template>

<style lang="scss" scoped>
.popup {
    overflow: hidden;

    #ads {
        display: block;
        height: 162px;
        background-color: #000;
        border: none;
        width: 100%;
        overflow: hidden;
    }

    #website {
        width: 100% !important;
        background-color: #fff;

        &.nav {
            height: calc(100vh - 42px - 38px - 34px);
        }

        &.fish {
            height: calc(100vh - 39px - 162px - 57px);
        }

        &.vertical {
            height: calc(100vh - 39px) !important;
        }
    }
}
</style>